package net

import (
	"gitee.com/cjianwen/go/demo/socks_v2/raft_demo/server/consts"
	"gitee.com/cjianwen/go/demo/socks_v2/raft_demo/server/global"
	"gitee.com/cjianwen/go/demo/socks_v2/raft_demo/server/proto"
	"gitee.com/cjianwen/go/logs"
	"gitee.com/cjianwen/go/service"
	"gitee.com/cjianwen/go/socks/v2"
)

type LisenServer struct {
	*service.Module
	msgReceiver *proto.MsgReceiver
	LeaderConn  *proto.ConnClient
}

func (s *LisenServer) Run() error {
	// fmt.Println("LisenServer.Run")
	s.msgReceiver.HandlePacks(proto.DispatchMsg)
	return nil
}

func (s *LisenServer) Init() error {
	logs.Println("LisenServer.Init")

	s.msgReceiver = proto.NewMsgReceiver()

	s.msgReceiver.OnConnect = func(conn *socks.ConnClient[proto.PackData, proto.UserData]) {
		logs.Println("LisenServer OnConnnect: ", conn.RemoteAddr())
	}

	s.msgReceiver.OnDisconnect = func(conn *socks.ConnClient[proto.PackData, proto.UserData]) {
		logs.Println("LisenServer OnDisconnnect: ", conn.RemoteAddr())
		if conn == global.LeaderConn {
			global.LeaderConn = nil
			logs.Println("与 Leader 断开连接")
		}
	}

	err := s.msgReceiver.ListenAndServe(global.ServerInfo.GetListenPort())
	if err != nil {
		panic(err)
	}

	return nil
}

func (s *LisenServer) Final() error {
	logs.Println("LisenServer.Final")
	s.msgReceiver.CloseServe()
	return nil
}

func init() {
	module := &service.Module{Name: "LisenServer", ModuleId: consts.MID_ListenServer}
	service.RegisterModule(&LisenServer{Module: module})
}
